package com.example.demo.util.converters.impl;

import com.example.demo.util.DateUtil;
import com.example.demo.util.converters.MyConverter;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Optional;

/**
 * @author 陈浩
 * @date 2021/1/9 15:28
 */

public class DateConverter implements MyConverter<Date> {
    @Override
    public Date convertToJavaData(String value, Field declaredField) throws Exception {
        DateTimeFormat annotation = declaredField.getAnnotation(DateTimeFormat.class);
        String format = Optional.ofNullable(annotation).map(DateTimeFormat::pattern).orElse("");
        return StringUtils.isEmpty(format) ? DateUtil.parseDate(value, (String) null) : DateUtil.parseDate(value, format);
    }


}
